﻿Imports System.Resources
Imports System.Threading
Imports Biz
Imports BLL


Public Class ctrlBackup

    Private _RM As ResourceManager
    Dim _strPath As String


    Public Sub SetIdioma()

        _RM = New ResourceManager("UI.Idiomas", System.Reflection.Assembly.GetExecutingAssembly)

        btnTomarBackup.Text = _RM.GetString("btnTomarBackup")
        btnRestaurar.Text = _RM.GetString("btnRestaurar")
        lblRealizarNuevoBackup.Text = _RM.GetString("strRealizarNuevoBackup")
        lblHistorial.Text = _RM.GetString("strHistorialDeBackups")
        lblTituloDescripcion.Text = _RM.GetString("strDescripcion") & ":"
        lblTituloDestino.Text = _RM.GetString("strDestino") & ":"
        lblTituloArchivo.Text = _RM.GetString("strNombreArchivo") & ":"
        lblTituloExtension.Text = _RM.GetString("strBkp")

        advTreeHistorialBackups.Columns("colId").Text = _RM.GetString("strNumero")
        advTreeHistorialBackups.Columns("colDescripcion").Text = _RM.GetString("strDescripcion")
        advTreeHistorialBackups.Columns("colPath").Text = _RM.GetString("strUbicacion")
        advTreeHistorialBackups.Columns("colFecha").Text = _RM.GetString("strFecha")
        advTreeHistorialBackups.Columns("colUsuario").Text = _RM.GetString("strUsuario")
        advTreeHistorialBackups.Refresh()

        SetAyudaContextual()

    End Sub

    Public Sub CargarGrilla()
        Dim oBackup As cBackup
        Dim colObjetos As Collection
        Dim oNode As DevComponents.AdvTree.Node


        advTreeHistorialBackups.BeginUpdate()

        advTreeHistorialBackups.Nodes.Clear()

        Try
            colObjetos = GestorBackup.Instance.Consultar

            If Not colObjetos Is Nothing Then

                For Each oBackup In colObjetos

                    oNode = New DevComponents.AdvTree.Node

                    oNode.Tag = oBackup.Bkp_Id
                    oNode.Text = oBackup.Bkp_Id
                    oNode.Cells.Add(New DevComponents.AdvTree.Cell(oBackup.Bkp_Descripcion))
                    oNode.Cells.Add(New DevComponents.AdvTree.Cell(oBackup.Bkp_Path))
                    oNode.Cells.Add(New DevComponents.AdvTree.Cell(oBackup.Bkp_Fecha))
                    oNode.Cells.Add(New DevComponents.AdvTree.Cell(oBackup.oUsuario.Usu_Nombre + " " + oBackup.oUsuario.Usu_Apellido))

                    advTreeHistorialBackups.Nodes.Add(oNode)

                Next
            End If

        Catch ex As Excepciones.BackupFalloConsulta
            Main.ManejarExcepcion(ex)
        Catch ex As Exception
            Main.ManejarExcepcion(ex)
        End Try

        advTreeHistorialBackups.EndUpdate()

        advTreeHistorialBackups.Refresh()

    End Sub

    Private Function ValidarForm() As Boolean
        Dim bValido As Boolean = True

        If txtDescripcion.Text.Trim = "" Then bValido = False
        If txtNombreArchivo.Text.Trim = "" Then bValido = False
        If crumBarDestino.SelectedItem Is Nothing Then bValido = False

        ValidarForm = bValido

        If bValido = False Then
            lblMensajes.Text = "Complete todos los datos requeridos..."
        End If

    End Function

    Private Sub CargarCrumBar()
        Dim myComputer As New DevComponents.DotNetBar.CrumbBarItem()

        myComputer.Text = "My Computer"
        myComputer.Image = Global.UI.My.Resources.Resource.computer
        crumBarDestino.Items.Add(myComputer)

        Dim drives() As IO.DriveInfo = IO.DriveInfo.GetDrives()

        For Each driveInfo As IO.DriveInfo In drives

            If driveInfo.DriveType <> IO.DriveType.Fixed Then
                Continue For
            End If

            Dim node As New DevComponents.DotNetBar.CrumbBarItem()
            node.Tag = driveInfo
            node.Text = "Local Disk " & driveInfo.Name.Replace("\", "")
            node.Image = Global.UI.My.Resources.Resource.hdd
            myComputer.SubItems.Add(node)
        Next driveInfo

        crumBarDestino.SelectedItem = myComputer

    End Sub

    Private Sub crumBarDestino_SelectedItemChanged(sender As Object, e As DevComponents.DotNetBar.CrumbBarSelectionEventArgs) Handles crumBarDestino.SelectedItemChanged

        Dim parent As DevComponents.DotNetBar.CrumbBarItem = e.NewSelectedItem
        If parent Is Nothing OrElse parent.SubItems.Count > 0 Then
            Return
        End If

        Dim dirInfo As IO.DirectoryInfo = Nothing
        If TypeOf parent.Tag Is IO.DriveInfo Then
            Dim driveInfo As IO.DriveInfo = CType(parent.Tag, IO.DriveInfo)
            dirInfo = driveInfo.RootDirectory
        ElseIf TypeOf parent.Tag Is IO.DirectoryInfo Then
            dirInfo = CType(parent.Tag, IO.DirectoryInfo)
        End If

        Dim subDirectories() As IO.DirectoryInfo = dirInfo.GetDirectories()
        For Each directoryInfo As IO.DirectoryInfo In subDirectories
            Dim node As New DevComponents.DotNetBar.CrumbBarItem()
            node.Tag = directoryInfo
            node.Text = directoryInfo.Name
            node.Image = Global.UI.My.Resources.Resource.folder
            parent.SubItems.Add(node)
        Next directoryInfo
    End Sub

    Private Sub btnTomarBackup_Click(sender As Object, e As EventArgs) Handles btnTomarBackup.Click
        Dim itemSelected As DevComponents.DotNetBar.CrumbBarItem
        Dim oBackup As cBackup

        Dim strAux1 As String = ""
        Dim strAux2 As String = ""
        Dim strAux3 As String = ""
        Dim strAux4 As String = ""

        Dim strPath As String

        Dim bResultado As Boolean


        Try

            If Not GestorUsuario.Instance.TienePermiso(AppCurrentState.UsuarioLogueado, New cPatente(Utils.Enumeradores.Patentes.Backup)) Then
                frmMainMetro.StatusBarLabel.Text = "El usuario no posee permisos suficientes para realizar esta operación"
                Exit Sub
            End If


            If ValidarForm() Then
                itemSelected = crumBarDestino.SelectedItem

                If Not itemSelected Is Nothing Then
                    strAux1 = itemSelected.Tag.ToString
                    If Not itemSelected.Parent Is Nothing Then
                        strAux2 = itemSelected.Parent.Tag.ToString

                        If Not itemSelected.Parent.Parent Is Nothing Then
                            strAux3 = itemSelected.Parent.Parent.Tag.ToString

                            If Not itemSelected.Parent.Parent.Parent Is Nothing Then
                                strAux4 = itemSelected.Parent.Parent.Parent.Tag.ToString
                            End If
                        End If
                    End If
                End If

                strPath = strAux4 + strAux3 + strAux2 + strAux1


                oBackup = New cBackup
                oBackup.Bkp_Descripcion = txtDescripcion.Text.Trim
                oBackup.Bkp_Path = strPath + "\" + txtNombreArchivo.Text.Trim + ".BAK"
                oBackup.oUsuario.Usu_Legajo = AppCurrentState.UsuarioLogueado.Usu_Legajo

                Try
                    bResultado = GestorBackup.Instance.doBackup(oBackup)
                    If bResultado Then
                        GestorBitacora.Instance.Loguear(New cBitacora_Usuario(AppCurrentState.UsuarioLogueado.Usu_Legajo, Utils.Enumeradores.Bitacora.Backup))
                    End If

                    If bResultado Then
                        txtDescripcion.Text = ""
                        txtNombreArchivo.Text = ""
                    End If

                Catch ex As Excepciones.BackupFalloNuevo
                    Main.ManejarExcepcion(ex)
                Catch ex As Exception
                    Main.ManejarExcepcion(ex)
                End Try

                CargarGrilla()
            End If

        Catch ex As Excepciones.UsuarioFalloConsultaTieneAcceso
            Main.ManejarExcepcion(ex)
        Catch ex As Exception
            Main.ManejarExcepcion(ex)
        End Try

    End Sub

    Private Sub btnRestaurar_Click(sender As Object, e As EventArgs) Handles btnRestaurar.Click
        Dim oBackup As cBackup = New cBackup
        Dim bResultado As Boolean = False


        Try

            If Not GestorUsuario.Instance.TienePermiso(AppCurrentState.UsuarioLogueado, New cPatente(Utils.Enumeradores.Patentes.Restore)) Then
                frmMainMetro.StatusBarLabel.Text = "El usuario no posee permisos suficientes para realizar esta operación"
                Exit Sub
            End If


            If Not advTreeHistorialBackups.SelectedNode Is Nothing Then
                oBackup.Bkp_Path = advTreeHistorialBackups.SelectedNode.Cells(2).Text.Trim

                Try
                    bResultado = GestorBackup.Instance.doRestore(oBackup)
                    If bResultado Then
                        GestorBitacora.Instance.Loguear(New cBitacora_Usuario(AppCurrentState.UsuarioLogueado.Usu_Legajo, Utils.Enumeradores.Bitacora.Restore))
                    End If

                Catch ex As Excepciones.BackupFalloRestore
                    Main.ManejarExcepcion(ex)
                Catch ex As Exception
                    Main.ManejarExcepcion(ex)
                End Try

                CargarGrilla()

            End If


        Catch ex As Excepciones.UsuarioFalloConsultaTieneAcceso
            Main.ManejarExcepcion(ex)
        Catch ex As Exception
            Main.ManejarExcepcion(ex)
        End Try

    End Sub

    Public Sub SetAyudaContextual()
        _RM = New ResourceManager("UI.AyudaContextual", System.Reflection.Assembly.GetExecutingAssembly)

        HelpProviderForm.SetHelpString(advTreeHistorialBackups, "Lista de copias de seguridad disponibles")

    End Sub

    Public Sub Inicializar()

        lblMensajes.Text = ""

        CargarCrumBar()
        CargarGrilla()
        SetAyudaContextual()

    End Sub

End Class
